<?php

namespace app\api\logic;

use app\admin\logic\system\SystemConfigLogic;
use app\basic\BaseLogic;
use app\basic\model\Sms;
use exception\ApiException;
use support\Request;
use support\sms\Driver as SmsDriver;

class SmsLogic extends BaseLogic
{
     /**
     * 验证码有效时长
     * @var int
     */
    protected static $expire = 300;

    /**
     * 最大允许检测的次数
     * @var int
     */
    protected static $maxCheckNums = 10;

     private $configLogic;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->configLogic = new SystemConfigLogic();
        $this->model = new Sms();
    }

    /**
     * 发送短信
     */
    public function smsBase()
    {
        $config = $this->configLogic->getConfig("sms")['value'];
        $StorageDriver = new SmsDriver($config);
        if(!$StorageDriver->sendSms()){
            throw new ApiException('发送短信失败' . $StorageDriver->getError());
        }
        $ip = request()->getRealIp(true);
        // 短信发送成功 写入信息
        Sms::create(['event' => Request()->post("type"), 'mobile' => Request()->post("phone"), 'code' => $StorageDriver->getCode(), 'ip' => $ip, 'create_time' => time()]);
        return true;
    }

    /**
     * 校验验证码
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码
     * @param   string $event  事件
     * @return  boolean
     */
    public static function check($mobile, $code, $event = 'default')
    {
        $time = time() - self::$expire;
        $sms = Sms::where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        if ($sms) {
            if (strtotime($sms['create_time']) > $time && $sms['times'] <= self::$maxCheckNums) {
                $correct = $code == $sms['code'];
                if (!$correct) {
                    $sms->times = $sms->times + 1;
                    $sms->save();
                    return false;
                }else{
                    return true;
                }
            } else {
                // 过期则清空该手机验证码
                self::flush($mobile, $event);
                return false;
            }
        } else {
            return false;
        }
    }

      /**
     * 清空指定手机号验证码
     *
     * @param   int    $mobile 手机号
     * @param   string $event  事件
     * @return  boolean
     */
    public static function flush($mobile, $event = 'default')
    {
        Sms::where(['mobile' => $mobile, 'event' => $event])
            ->delete();
        return true;
    }

}